/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package executingimpl.executeservice;

import executing.ExecutionResultFactory;
import executing.IExecutor;
import executing.IProcessRunner;
import executingimpl.runner.ExecuteProcessRunner;
import executor.ExecutingException;
import executor.ExecutionItem;
import executor.ExecutionResult;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ryuju
 */
public class JavaClassExecutor implements IExecutor{

    @Override
    public ExecutionResult execute(ExecutionItem execItem, String tempDir) throws ExecutingException{
        
        File classFile = new File(tempDir, "Main.class");
        ExecutionResult execResult = ExecutionResultFactory.getEmptyExecutionResult();
        if(false == classFile.exists())
        {
            throw new ExecutingException("class file not exists");
        }
        
        List<String> cmdList = makeCommandList(tempDir);
        IProcessRunner execRunner = new ExecuteProcessRunner();
        
        try
        {
            List<String> outputs = new ArrayList<String>();
            int totalExecTime = 0;
            for(String input : execItem.inputs)
            {
                ExecutionResult er = execRunner.run(cmdList, input);
                if(er.errOccured)
                {
                    outputs.add(er.errMsg);
                }
                else
                {
                    outputs.add(er.outputs[0]);
                }
                totalExecTime += er.execTime;
            }
            
            execResult.execTime = totalExecTime;
            execResult.execCompleted = true;
            execResult.outputs = new String[outputs.size()];
            execResult.outputs = outputs.toArray(execResult.outputs);
            
        }
        catch(Exception e)
        {
            execResult.errMsg = e.getMessage();
            execResult.errOccured = true;
            execResult.execCompleted = false;
        }
        
        return execResult;
        
    }
    
    private List<String> makeCommandList(String classPath)
    {
        ArrayList<String> cmdList=  new ArrayList<String>();
        
        cmdList.add("java");
        cmdList.add("-classpath");
        cmdList.add(classPath);
        cmdList.add("Main");
        
        return cmdList;
    }
    
}
